package pt.iscte.pcd.nestedclasses;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JComponent;

public class Board extends JComponent {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int nLines;
	private int nCol;
	private int selected = -1;

	public Board(int nLines, int nCol) {
		super();
		this.nLines = nLines;
		this.nCol = nCol;
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		int dx = getWidth() / (nCol);
		int dy = getHeight() / (nLines);
		g.drawLine(50, 5, 100, 5);
		for (int i = 1; i < nLines; i++) {
			g.drawLine(0, i * dy, getWidth(), i * dy);
		}
		for (int i = 1; i < nCol; i++) {
			g.drawLine(i * dx, 0, i * dx, getHeight());
		}
		for (int i = 0; i < nCol * nLines; i++) {
			String label = "" + i;
			int w = g.getFontMetrics().stringWidth(label) / 2;
			int h = g.getFontMetrics().getDescent();
			int x = (int) ((i % nCol + .5) * dx - w);
			int y = (int) ((i / nCol + .5) * dy + h);
			g.drawString(label, x, y);
		}
		if (selected >= 0) {
			g.setColor(Color.DARK_GRAY);
			g.fillRect((int) ((selected % nCol) * dx),
					(int) ((selected / nCol) * dy), dx, dy);
			g.setColor(Color.red);
			String label = selected + "";
			int w = g.getFontMetrics().stringWidth(label) / 2;
			int h = g.getFontMetrics().getDescent();
			int x = (int) ((selected % nCol + .5) * dx - w);
			int y = (int) ((selected / nCol + .5) * dy + h);
			g.drawString(label, x, y);
			g.setColor(Color.black);
		}
	}

	public void setSelected(Point point) {
		int col = (int) (point.getX() / (getWidth() / nCol));
		int lin = (int) (point.getY() / (getHeight() / nLines));
		selected = col + lin * nCol;
		System.out.println(selected + ": col= " + col + ", lin= " + lin);
		repaint();
	}
}
